package com.guozcc.bootweb.demo.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.guozcc.bootweb.demo.component.DemoComponent;
import com.guozcc.bootweb.demo.domain.XszJdkxZbtj;
import com.guozcc.bootweb.platform.common.PageUtils;
import com.guozcc.bootweb.platform.annotation.Trade;
import com.guozcc.bootweb.platform.common.ResultUtils;
import com.guozcc.bootweb.platform.dto.response.ResultVO;
import com.guozcc.bootweb.demo.exceltemplate.ExcelTemplate;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/demo/")
@Api(tags = {"测试模块"})
public class DemoController {

    private final Logger log = LoggerFactory.getLogger(this.getClass());


    @Autowired
    private DemoComponent demoComponent;

    @ApiOperation(
            value="DEMO_文件下载，EXCEL文件解析测试",//接口名称
            notes="生成EXCEL测试,生成到本地，给前端返回文件流",//接口详细描述
            response = ResultVO.class,
            produces="application/json")
    @Trade(tradeCode="demo0001",checkLogin = false,method = RequestMethod.GET)
    public ResponseEntity</*InputStreamResource*/ByteArrayResource> demo0001(HttpServletResponse httpServletResponse) throws Exception {

        List<ExcelTemplate> studentTemplate = new ArrayList<ExcelTemplate>(){{
            add(new ExcelTemplate(){{
                setId("1001");
                setName("周星星");
                setGender("男");
                setAge(12);
            }});
            add(new ExcelTemplate(){{
                setId("1002");
                setName("吴孟达");
                setGender("女");
                setAge(13);
            }});
            add(new ExcelTemplate(){{
                setId("1003");
                setName("林青霞");
                setGender("男");
                setAge(15);
            }});
            add(new ExcelTemplate(){{
                setId("1004");
                setName("查扎辉");
                setGender("男");
                setAge(88);
            }});
        }};
        //本地生成文件
//        String fileName = "C://Users/Administrator/Desktop/student.xlsx";
//        EasyExcel.write(fileName,ExcelTemplate.class).sheet("明星").doWrite(studentTemplate);
        //前端返回文件流
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        EasyExcel.write(bos,ExcelTemplate.class).sheet("明星").doWrite(studentTemplate);


        return ResponseEntity
                .ok()
                .headers(new HttpHeaders(){{
                    add("Cache-Control","no-cache,no-store,must-revalidate");
                    add("Content-Disposition","attachment;filename=student.xlsx");
                    add("Pragma","no-cache");
                    add("Expires","0");
                }})
                .contentLength(bos.size())
                .contentType(MediaType.parseMediaType("application/cotet-stream"))
                .body(new ByteArrayResource(bos.toByteArray()));
    }

    @ApiOperation(
            value="DEMO_文件上传，EXCEL生成测试",//接口名称
            notes="上传EXCEL文件，读取内容按LIST返回",//接口详细描述
            response = ResultVO.class,
            produces="application/json")
    @Trade(tradeCode="demo0002",checkLogin = false)
    public @ResponseBody ResultVO<JSONObject> demo0002(@RequestPart("file")MultipartFile file,@RequestPart String  filedesc) throws Exception {
//        String fileContext = FileUtils.inputStream2String(file.getInputStream(),"UTF-8");
        List<ExcelTemplate> studentTemplate = new ArrayList<ExcelTemplate>();
        EasyExcel
                .read(file.getInputStream())
                .head(ExcelTemplate.class)
                .sheet("明星")
                .registerReadListener(new AnalysisEventListener<ExcelTemplate>() {
                    @Override
                    public void invoke(ExcelTemplate o, AnalysisContext analysisContext) {
                        studentTemplate.add(o);
                    }

                    @Override
                    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                        log.info("文件已读取完毕");
                    }
                })
                .doRead();
        return ResultUtils.success(new JSONObject()
                .fluentPut("filedesc",filedesc)
                .fluentPut("studentTemplate",studentTemplate));
    }


    @ApiOperation(
            value="DEMO_CUDL_列表查询",//接口名称
            notes="列表查询",//接口详细描述
            response = ResultVO.class,
            produces="application/json")
    @Trade(tradeCode="demo0003_list",checkLogin = false)
    public @ResponseBody ResultVO<List<XszJdkxZbtj>> demo0003_list(@RequestBody(required = false)XszJdkxZbtj param) throws Exception {
        com.guozcc.bootweb.demo.pojo.XszJdkxZbtj xszJdkxZbtj = JSONObject.parseObject(JSON.toJSONString(param), com.guozcc.bootweb.demo.pojo.XszJdkxZbtj.class);
        List<XszJdkxZbtj> list = demoComponent.getList(xszJdkxZbtj).stream().map(o -> JSONObject.parseObject(JSON.toJSONString(o),XszJdkxZbtj.class)).collect(Collectors.toList());
        return ResultUtils.success(list);
    }
    @ApiOperation(
            value="DEMO_CUDL_新增、事务测试",//接口名称
            notes="新增、事务是否生效",//接口详细描述
            response = ResultVO.class,
            produces="application/json")
    @Trade(tradeCode="demo0003_add",checkLogin = false)
    public @ResponseBody ResultVO demo0003_add(@RequestBody(required = true)XszJdkxZbtj param) throws Exception {
        com.guozcc.bootweb.demo.pojo.XszJdkxZbtj xszJdkxZbtj = JSONObject.parseObject(JSON.toJSONString(param), com.guozcc.bootweb.demo.pojo.XszJdkxZbtj.class);
        xszJdkxZbtj.setTjDate(new Date());
        demoComponent.add(xszJdkxZbtj);
        return ResultUtils.success(null);
    }

    @ApiOperation(
            value="DEMO_分页查询测试",//接口名称
            notes="分页以及函数式编程用法",//接口详细描述
            response = ResultVO.class,
            produces="application/json")
    @Trade(tradeCode="demo0004",checkLogin = false)
    public @ResponseBody ResultVO<PageInfo<com.guozcc.bootweb.demo.pojo.XszJdkxZbtj>> demo0004() throws Throwable {

        PageInfo<com.guozcc.bootweb.demo.pojo.XszJdkxZbtj> pageInfoAll = PageUtils.getInstance().executePageNoParam(2, 2, () -> demoComponent.getAll());
        log.info("数据总条数："+pageInfoAll.getTotal());
        log.info("单页最大条数："+pageInfoAll.getPageSize());
        log.info("总页数："+pageInfoAll.getPages());
        log.info("当前页："+pageInfoAll.getPageNum());
        log.info("当前页条数："+pageInfoAll.getSize());
        log.info("结果集条数:"+pageInfoAll.getList().size());


        PageInfo<com.guozcc.bootweb.demo.pojo.XszJdkxZbtj> pageInfoMblx =  PageUtils.getInstance().executePageByParam(1, 2, com.guozcc.bootweb.demo.pojo.XszJdkxZbtj.builder().dlrs(0).build(), s -> demoComponent.getList(s));
        log.info("数据总条数："+pageInfoMblx.getTotal());
        log.info("单页最大条数："+pageInfoMblx.getPageSize());
        log.info("总页数："+pageInfoMblx.getPages());
        log.info("当前页："+pageInfoMblx.getPageNum());
        log.info("当前页条数："+pageInfoMblx.getSize());
        log.info("结果集条数:"+pageInfoMblx.getList().size());
        return ResultUtils.success(pageInfoMblx);
    }
}
